package com.cmcc.driver.ui.dialog

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import com.cmcc.driver.R
import com.cmcc.driver.databinding.DialogAppAlertBinding
import com.cmcc.driver.databinding.DialogInputAmountBinding
import com.cmcc.shared.utils.clickWithTrigger
import com.cmcc.shared.utils.showToast

class AppInputDialog(context: Context) {

    private var context: Context = context
    private val binding: DialogInputAmountBinding =
        DialogInputAmountBinding.inflate(LayoutInflater.from(context), null, false)

    private val dialog = Dialog(context, R.style.AppDialogStyle)

    init {
        //        val inflater = LayoutInflater.from(context)
        dialog.setContentView(binding.root)
        if (context is Activity) {
            val m = context.windowManager
            val d = m.defaultDisplay
            val p = dialog.window!!.attributes
            dialog.window?.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            p.width = (d.width * 0.9).toInt()
            dialog.window!!.attributes = p
            binding.amount.text.filters = arrayOf(PointLengthFilter())
            binding.amount.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    if (s.isNullOrBlank()) {
                        binding.amount.alpha = 0.6f
                    } else {
                        binding.amount.alpha = 1f
                    }
                }

                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {

                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                }
            })
        }

    }

    fun setOnInputListener(bountyFee: String?, listener: OnInputListener): AppInputDialog {
        binding.bountyFeeTv.text = "+ ${bountyFee ?: 0}".plus(context.getString(R.string.tip_order))
        binding.positiveButton.clickWithTrigger { view ->
            run {
                if (binding.amount.text.toString().isNotEmpty()) {
                    listener.onInput(binding.amount.text.toString())
                    binding.amount.text.clear()
                    dialog.dismiss()
                } else {
                    showToast(context, context.getString(R.string.plz_input_calc_number))
                }
            }
        }
        return this
    }

    fun show() {
        dialog.show()
    }

    interface OnInputListener {
        fun onInput(text: String)
    }

}